<template>
    <div>
        <div><h1>添加抽奖活动</h1></div>
        <div>
            <el-form
                ref="ruleFormRef"
                style="max-width: 1200px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
            >
                <el-form-item label="活动名称" prop="activeName">
                    <el-input v-model="ruleForm.activeName" />
                </el-form-item>
                <el-form-item label="活动时间" prop="activeTime">
                    <el-date-picker
                        v-model="ruleForm.activeTime"
                        type="datetimerange"
                        start-placeholder="开始时间"
                        end-placeholder="截止时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>

                <el-form-item label="参与用户" prop="userFlag">
                    <el-radio-group v-model="ruleForm.userFlag">
                        <el-radio v-for="item in joinUserList" :value="item.dictValue" :key="item.dictId">{{item.dictName}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="活动免费抽奖次数" prop="freeTimes">
                    <el-input v-model="ruleForm.freeTimes" />
                </el-form-item>

                <el-form-item label="规则选择" prop="name">
                    <el-table :data="ruleList" stripe style="width: 100%">
                        <el-table-column prop="date" label="序号" width="100" />
                        <el-table-column
                            prop="ruleImage"
                            label="图片"
                            width="120"
                        >
                        <template #default="scope">
                            <img
                                v-if="scope.row.ruleImage"
                                :src="scope.row.ruleImage"
                                alt="活动图片"
                                style="width: 50px; height: 50px"
                            />
                        </template>
                        </el-table-column>
                        <el-table-column
                            prop="ruleName"
                            label="名称"
                            width="120"
                        />
                        <el-table-column
                            prop="winProd"
                            label="奖品"
                            width="120"
                        />
                        <el-table-column
                            prop="winImage"
                            label="中奖弹窗图片"
                            width="120"
                        >
                        <template #default="scope">
                            <img
                                v-if="scope.row.winImage"
                                :src="scope.row.winImage"
                                alt="活动图片"
                                style="width: 50px; height: 50px"
                            />
                        </template>
                        </el-table-column>
                        <el-table-column
                            prop="prodNum"
                            label="数量"
                            width="120"
                        />
                        <el-table-column
                            prop="winChance"
                            label="奖品概率"
                            width="120"
                        />
                        <el-table-column label="操作" />
                    </el-table>
                    <div>
                        <el-button type="primary" @click="onAddRule"
                            >添加规则</el-button
                        >
                    </div>
                </el-form-item>

                <el-form-item label="中奖名单" prop="winFlag">
                    <el-switch
                        v-model="ruleForm.winFlag"
                        active-text="开启"
                        inactive-text="关闭"
                        :active-value="0"
                        :inactive-value="1"
                    />
                </el-form-item>

                <el-form-item label="中奖记录" prop="winRecord">
                    <el-switch
                        v-model="ruleForm.winRecord"
                        active-text="开启"
                        inactive-text="关闭"
                        :active-value="0"
                        :inactive-value="1"
                    />
                </el-form-item>

                <el-form-item label="活动状态" prop="activeStatus">
                    <el-switch
                        v-model="ruleForm.activeStatus"
                        active-text="开启"
                        inactive-text="关闭"
                        :active-value="0"
                        :inactive-value="1"
                    />
                </el-form-item>

                <el-form-item label="活动规则" prop="desc">
                    <div style="border: 1px solid #ccc">
                        <Toolbar
                            style="border-bottom: 1px solid #ccc"
                            :editor="editorRef"
                            :defaultConfig="toolbarConfig"
                            :mode="mode"
                        />
                        <Editor
                            style="height: 500px; overflow-y: hidden"
                            v-model="ruleForm.activeContent"
                            :defaultConfig="editorConfig"
                            :mode="mode"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        创建活动
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="添加规则" width="500">
                <el-form :model="form">
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="form.ruleName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="活动图片"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            :show-file-list="false"
                            :headers="headers"
                            :on-success="handleAvatarSuccess1"
                        >
                            <img
                                v-if="imageUrl1"
                                :src="imageUrl1"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="奖品" :label-width="formLabelWidth">
                        <el-input v-model="form.winProd" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="中奖弹窗图片"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            :show-file-list="false"
                            :headers="headers"
                            :on-success="handleAvatarSuccess2"
                        >
                            <img
                                v-if="imageUrl2"
                                :src="imageUrl2"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="数量" :label-width="formLabelWidth">
                        <el-input v-model="form.prodNum" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="精品概率"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.winChance" autocomplete="off" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >关闭</el-button
                        >
                        <el-button type="primary" @click="onSubmitAddRule">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { addActive,getDictList } from "@/api/api";
import { useRouter } from "vue-router"; // 导入 useRouter 钩子函数


const router = useRouter();
const imageUrl1 = ref("");
const imageUrl2 = ref("");
const headers = ref({
    token: sessionStorage.getItem("token") || "",
})

const mode = "default";
const joinUserList = ref<any>([]); // 参与用户列表

interface RuleForm {
    activeContent: string;
    activeName: string;
    activeStatus: number;
    activeTime: string;
    beginTime: string;
    endTime: string;
    freeTimes: number;
    userFlag: number;
    winFlag: number;
    winRecord: number;
    ruleList: [];
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    activeContent: "",
    activeName: "",
    activeStatus: 0,
    activeTime: "",
    beginTime: "",
    endTime: "",
    freeTimes: 0,
    ruleList: [],
    userFlag: 0,
    winFlag: 0,
    winRecord: 0,
});

const ruleList = ref<any>([]);

const rules = reactive<FormRules<RuleForm>>({
    activeName: [
        {
            required: true,
            message: "请输入活动名称",
            trigger: "blur",
        },
    ],
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
});

const handleAvatarSuccess1: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //imageUrl1.value = URL.createObjectURL(uploadFile.raw!);
    imageUrl1.value = response.data;
};

const handleAvatarSuccess2: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //imageUrl2.value = URL.createObjectURL(uploadFile.raw!);
    imageUrl2.value = response.data;
};

const onAddRule = () => {
    Object.assign(form, {
        prodNum: 0,
        ruleImage: "",
        ruleName: "",
        winChance: 0,
        winImage: "",
        winProd: "",
    });
    imageUrl1.value = "";
    imageUrl2.value = "";
    dialogFormVisible.value = true;
};

const onSubmitAddRule = () => {
    const rule: any = {};
    // 克隆一个对象
    Object.assign(rule, form);
    rule.ruleImage = imageUrl1.value;
    rule.winImage = imageUrl2.value;
    ruleList.value.push(rule);

    // 清空表单
    Object.assign(form, {
        prodNum: 0,
        ruleImage: "",
        ruleName: "",
        winChance: 0,
        winImage: "",
        winProd: "",
    });
    imageUrl1.value = "";
    imageUrl2.value = "";
};

// 提交添加抽奖活动的表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 表单校验通过了
            ruleForm.ruleList = ruleList.value;
            addActive(ruleForm).then((res) => {
                if (res.data.code == 200) {
                    console.log("添加成功", res);
                    ElMessage.success("添加成功");
                    router.push("/home/active");
                } else {
                    console.log("添加失败", res);
                }
            });
        } else {
            // 表单校验没通过
            console.log("error submit!", fields);
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
    // 获取参加用户字典
    getDictList(5).then(res => { 
        joinUserList.value = res.data.data;
    })
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
